﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Linq;
using System.ServiceProcess;
using System.Text;
using System.ServiceModel;
using Informant.Services.SmsMessaging;
using Informant.Services;

namespace Informant.Hosts.Windows
{
	public partial class InformantWinService : ServiceBase
	{
		ServiceHost _aggregateServiceHost;
		SmsService _aggregateService;

		/// <summary>
		/// Initializes a new instance of the <see cref="InformantWinService"/> class.
		/// </summary>
		public InformantWinService()
		{
			InitializeComponent();
		}

		/// <summary>
		/// When implemented in a derived class, executes when a Start command is sent to the service by the Service Control Manager (SCM) or when the operating system starts (for a service that starts automatically). Specifies actions to take when the service starts.
		/// </summary>
		/// <param name="args">Data passed by the start command.</param>
		protected override void OnStart(String[] args)
		{
			//System.Diagnostics.Debugger.Launch();
			StartSmsService();
		}
		/// <summary>
		/// When implemented in a derived class, executes when a Stop command is sent to the service by the Service Control Manager (SCM). Specifies actions to take when a service stops running.
		/// </summary>
		protected override void OnStop()
		{
			if (_aggregateServiceHost != null)
			{
				_aggregateServiceHost.Close();
				_aggregateServiceHost = null;
			}
			if (_aggregateService != null)
			{
				IDisposable disposable = _aggregateService as IDisposable;
				if (disposable != null)
				{
					disposable.Dispose();
				}
				_aggregateService = null;
			}
		}

		/// <summary>
		/// Starts the SMS service.
		/// </summary>
		private void StartSmsService()
		{
			if (_aggregateServiceHost == null
				|| _aggregateServiceHost.State != CommunicationState.Opened
				|| _aggregateServiceHost.State != CommunicationState.Opening)
			{
				_aggregateServiceHost = new ServiceHost(typeof(SmsService));
				_aggregateServiceHost.Open();
			}
		}
	}
}
